import React, { useEffect, useState, useRef } from 'react'
import {
  Table,
  TreeSelect,
  Space,
  Popover,
  Modal,
  Input,
  DatePicker,
  message
} from 'antd'
import _ from 'lodash'
import { changePanesAction, changeRecordAction } from '&/store/actions'
import { postDeviceAlarmUpdatew } from '&/api/electricity'
import { connect } from 'react-redux'
import { getColumns1 } from './index-data'
import { getList1 } from './index-query'
import Filter from '&/components/Filter'
import { filterOptions1 } from './filterOptions'
import Container from '@/appComponents/Container'
import './index.scss'
import { QuestionCircleOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import ModalForm from '../NewSynAlarmListSecond/ModalFrom'
const mapStateToProps = (state) => {
  return {
    getFiveViewReducer: state.getFiveViewReducer,
    getPanesReducer: state.getPanesReducer,
    getRecordReducer: state.getRecordReducer
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    changePanesAction: (...args) => dispatch(changePanesAction(...args)),
    changeRecordAction: (...args) => dispatch(changeRecordAction(...args))
  }
}

const EnterpriseElectricityMonitorList = () => {
  const [list1, setList1] = useState([])
  const [pageInfo, setPageInfo] = useState({
    page: 1,
    pageSize: 20,
    total: 0
  })
  const [visible, setVisible] = useState(false)
  const value = JSON.parse(localStorage.getItem('user'))
  const [list1Loading, setList1Loading] = useState(false)
  const filterRef = useRef()
  const [records, setRecords] = useState()
  const [downloadData, setDownloadData] = useState([])
  const [feedbackValue, setFeedbackValue] = useState()
  const [feedbackTime, setFeedbackTime] = useState()
  const feedback = (record) => {
    setRecords(record)
    setVisible(true)
  }
  const handleOk = async () => {
    if (feedbackValue && feedbackTime) {
      let res = await postDeviceAlarmUpdatew({
        rule_number: 2,
        feedback: feedbackValue,
        warn_id: records.warn_id,
        examination_time: feedbackTime
      })
      message.info(res)
      setVisible(false)
    } else {
      message.info('请填写反馈信息/选择时间')
    }
  }
  const columns1 = getColumns1(feedback)
  const renderContainerTitle = () => {
    const content = (
      <div style={{ marginBottom: 5, padding: 5 }}>
        <p>
          1.
          额定电度计算：每个设备的单点电度值，过滤0值（0.2以下的），然后求平均值以上数据的众数，视为设备额定电度，作为负荷判断和报警的基础数据。暂定滑动60天的数据
        </p>
        <p>
          2.日常产治污不同步计算规则：针对生产中的企业（暂定产污设备电度数据大于等于0.2），产污设备单点电度值大于等于额定电度*0.2，同时治污设备单点电度值小于额定电度*0.1
        </p>
      </div>
    )
    return (
      <Space>
        查询结果
        {/* <Popover
          content={content}
          title="产治污不同步的规则说明："
          placement="rightTop"
        >
          <QuestionCircleOutlined style={{ cursor: 'pointer' }} />
        </Popover> */}
      </Space>
    )
  }

  useEffect(() => {
    if (list1.length) {
      const data = list1.map((item) => {
        return {
          ...item,
          other_data:
            (item.other_data
              ? item.other_data?.map((d) => {
                  return `${d[1]}启用 \n `
                })
              : '') + `   ${item.dev_name}未同步开启`
        }
      })
      setDownloadData(data)
    }
  }, [list1])

  return (
    <Container>
      <Container.ContainerQuery title="查询条件">
        <Filter
          ref={filterRef}
          loading={list1Loading}
          showDownloadButton={true}
          downloadConfig={{
            name: '实时报警（规则二）列表',
            data: downloadData,
            columns: columns1
          }}
          options={filterOptions1}
          hasMarginBottom={false}
          filterItem={
            <div className="Filter-item">
              <span>区域选择</span>
              <TreeSelect
                style={{
                  width: '100%'
                }}
                dropdownStyle={{
                  maxHeight: 400,
                  overflow: 'auto'
                }}
                defaultValue={value.adm_id}
                onChange={(v) => {
                  const p = {
                    [v < 1000 ? 'county_id' : 'town_id']: v
                  }
                  if (v < 1000) {
                    p.town_id = false
                  } else {
                    p.county_id = false
                  }
                  filterRef.current.setParams(p)
                }}
                placeholder="请选择区域"
                treeData={filterOptions1.__dict.area}
              />
            </div>
          }
          hasBorder={false}
          search={getList1(setList1, setList1Loading, setPageInfo)}
        ></Filter>
      </Container.ContainerQuery>
      <Container.ContainerContent title={renderContainerTitle()}>
        <Table
          bordered
          size="small"
          loading={list1Loading}
          dataSource={list1}
          columns={columns1}
          pagination={{
            pageSize: 50,
            position: ['bottomCenter']
          }}
          scroll={{
            x: 'max-content',
            y: '62vh'
          }}
          rowKey={(row) => {
            return JSON.stringify(row)
          }}
        />
        <ModalForm
          records={records}
          visible={visible}
          setVisible={setVisible}
        />
        {/* <Modal
          title="反馈"
          destroyOnClose={true}
          open={visible}
          centered={true}
          width={600}
          onOk={handleOk}
          onCancel={() => setVisible(false)}
        >
          <Input
            onChange={(e) => {
              setFeedbackValue(e.target.value)
            }}
            placeholder="请输入反馈信息"
          />
          <DatePicker
            style={{ marginTop: 10 }}
            format="YYYY-MM-DD HH:00:00"
            showTime={{
              defaultValue: dayjs('00:00:00', 'HH:00:00')
            }}
            onChange={(_, c) => {
              setFeedbackTime(c)
            }}
          />
        </Modal> */}
      </Container.ContainerContent>
    </Container>
  )
}

const EnterpriseElectricityMonitorListConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
  null,
  {
    forwardRef: true
  }
)(EnterpriseElectricityMonitorList)
export default EnterpriseElectricityMonitorListConnect
